package aaa.update;

import aaa.database.Database;
import aaa.exception.AAAException;
import aaa.schedule.GuidScheduleUpdater;
import aaa.schedule.Schedule;
import aaa.schedule.ScheduleConstants;
import aaa.schedule.ScheduleUpdater;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class UpdateManager extends IntentService implements ScheduleConstants {
	
	protected Database db ;

	public UpdateManager() {
		super("AWLUpdater") ;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		this.db = new Database(this) ;
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
		String schedule = intent.getExtras().getString("aaa.schedule.name") ;
		try {
			//TODO Add internet connection test
			this.changeScheduleStatus(schedule, STATUS_UPDATING) ;
			Schedule newS = this.db.getScheduleWithName(schedule) ;
			newS.build(this) ;
			Schedule oldS = this.db.getScheduleWithName(schedule) ;
			oldS.build(this.db) ;
			this.db.setLastModifSchedule(oldS.getName()) ;
			ScheduleUpdater updater = new GuidScheduleUpdater(this) ;
			updater.compare(oldS, newS) ;
			updater.updateSchedule() ;
			this.changeScheduleStatus(schedule, STATUS_UPDATED) ;
		} catch (AAAException e) {
			this.changeScheduleStatus(schedule, STATUS_NOT_UPDATED, e) ;
		}// try
	}
	
	protected void changeScheduleStatus(String scheduleName, int newStatus) {
		this.sendBroadcast(this.buildBroadcast(scheduleName, newStatus)) ;
	}
	
	protected void changeScheduleStatus(String scheduleName, int newStatus, AAAException ex) {
		Intent intent = this.buildBroadcast(scheduleName, newStatus) ;
		intent.putExtra("aaa.schedule.name", ex) ;
		this.sendBroadcast(intent) ;
	}
	
	protected Intent buildBroadcast(String scheduleName, int newStatus) {
		Log.d("aaa" ,"Service running in thread : "+Thread.currentThread()) ;
		Log.d("aaa" ,"  Schedule "+scheduleName+" -> "+newStatus) ;
		this.db.setScheduleStatus(scheduleName, newStatus) ;
		Intent intent = new Intent("aaa.STATUS_UPDATE") ;
		intent.putExtra("aaa.schedule.name", scheduleName) ;
		intent.putExtra("aaa.schedule.status", newStatus) ;
		return intent ;
	}

}